package school.xauat.inscription_sys.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import school.xauat.inscription_sys.pojo.Bronzeware;
import school.xauat.inscription_sys.pojo.Inscription;
import school.xauat.inscription_sys.pojo.User;
import school.xauat.inscription_sys.pojo.vo.RespVo;
import school.xauat.inscription_sys.service.InscriptionService;
import school.xauat.inscription_sys.service.UserService;

import javax.servlet.http.HttpSession;
import java.util.List;

import static school.xauat.inscription_sys.errorcode.ErrorCode.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zsy
 * @since 2022-05-03
 */
@RestController
@RequestMapping("/inscription_sys/inscription")
public class InscriptionController {

    @Autowired
    InscriptionService inscriptionService;

    @Autowired
    UserService userService;


    @PostMapping("/add")
    public RespVo add(@RequestBody Inscription inscription, HttpSession session) {
        Object obj = session.getAttribute("user");
        if (obj == null) {
            return RespVo.error(ERROR_NO_LOGIN, getMsg(ERROR_NO_LOGIN));
        }
        User user = (User) obj;
        user = userService.getOne(new QueryWrapper<User>().eq("username", user.getUsername()));
        inscription.setUserId(user.getId());
        if (!checkAndValid(inscription)) {
            return RespVo.error(ERROR_ILLEGAL_PARAMS, getMsg(ERROR_ILLEGAL_PARAMS));
        }
        if (inscriptionService.save(inscription)) {
            return RespVo.ok();
        } else {
            return RespVo.error(ERROR_DB_UNKNOWN, getMsg(ERROR_DB_UNKNOWN));
        }
    }

    private boolean checkAndValid(Inscription inscription) {
        return inscription != null
                && inscription.getPicture() != null
                && inscription.getBronzewareId() != null
                && inscription.getWordId() != null
                && inscription.getInfo() != null
                && inscription.getUserId() != null;
    }

}

